package com.hup.minicontroller.common.util;

import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author hugan
 * @date 2021/5/23
 */
public abstract class NetUtil {

    /**
     * 获取局域网的网关地址
     *
     * @return defValue-解析异常时的返回值
     * @apiNote 只是简单的把获取到的ipv4.ip的第四位改成1而已,很多情况下是不准确的(路由器改了网关,安卓热点等)
     */
    public static String getGatewayIp(String defValue) {
        try {
            String address = InetAddress.getLocalHost().getHostAddress();
            if (StringUtils.isBlank(address)) return defValue;
            if ("127.0.0.1".equals(address)) return address;
            String[] split = address.split("\\.");
            if (split.length != 4) return defValue;
            return split[0] + "." + split[1] + "." + split[2] + ".1";
        } catch (UnknownHostException e) {
            return defValue;
        }
    }
}
